import {
  PaginationProps,
  Grid,
  Pagination,
  Skeleton,
  Card,
  Form,
  Input,
  Select,
  Button,
  Space
} from '@arco-design/web-react';
import React, { useEffect, useState } from 'react';
import instance from '@/utils/request';
import FactoryStructurePanel from '@/components/FactoryStructurePanel';
import { NavLink } from 'react-router-dom';
import { IconRefresh, IconSearch } from '@arco-design/web-react/icon';
import useLocale from '@/utils/useLocale';
import { ActivateStateOptions, EnabledOptions, RunningStateOptions } from '@/constants/options';
import { defaultPaginationProps } from '@/constants/defaults';
import {
  resolveDeviceActivateState,
  resolveDeviceRunningState,
  resolveDeviceRunningStateColor
} from '@/constants/functions';

const { Row, Col } = Grid;
const locale = {
  'en-US': {},
  'zh-CN': {
    'label.id': '设备id',
    'label.code': '设备编码',
    'label.name': '设备名称',
    'label.remark': '设备描述',
    'label.enabled': '设备启用',
    'label.activateState': '激活状态',
    'label.runningState': '运行状态',

    'placeholder.id': '请输入设备id',
    'placeholder.code': '请输入设备编码',
    'placeholder.name': '请输入设备名称',
    'placeholder.remark': '请输入设备描述',
    'placeholder.enabled': '请输入设备启用',
    'placeholder.activateState': '请选择激活状态',
    'placeholder.runningState': '请选择运行状态',

    'button.search': '搜索',
    'button.reset': '重置'
  }
};

const SearchForm = (props: {
  onSubmit: ({}) => void,
  onReset: () => void,
}) => {
  const t = useLocale(locale);
  const [form] = Form.useForm();
  return (
    <Form form={form} style={{ padding: '1rem', background: 'white' }}>
      <Row style={{ display: 'flex' }}>
        <Grid style={{ flexGrow: '1' }} cols={4} colGap={12} rowGap={16}>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.id']} field="id">
              <Input placeholder={t['placeholder.id']} allowClear />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.code']} field="code">
              <Input placeholder={t['placeholder.code']} allowClear />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.name']} field="name">
              <Input
                allowClear
                placeholder={t['placeholder.name']}
              />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.remark']} field="remark">
              <Input
                allowClear
                placeholder={t['placeholder.remark']}
              />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.enabled']} field="enabled">
              <Select
                placeholder={t['placeholder.enabled']}
                options={EnabledOptions}
                allowClear
              />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.activateState']} field="activateState">
              <Select
                placeholder={t['placeholder.activateState']}
                options={ActivateStateOptions}
                allowClear
              />
            </Form.Item>
          </Grid.GridItem>
          <Grid.GridItem>
            <Form.Item noStyle label={t['label.runningState']} field="runningState">
              <Select
                placeholder={t['placeholder.runningState']}
                options={RunningStateOptions}
                allowClear
              />
            </Form.Item>
          </Grid.GridItem>
        </Grid>
        <Row style={{ display: 'inline-flex', marginLeft: '1rem' }} justify={'center'}>
          <Space direction={'vertical'}>
            <Button type="primary" icon={<IconSearch />} onClick={() => props.onSubmit(form.getFieldsValue())}>
              {t['button.search']}
            </Button>
            <Button icon={<IconRefresh />} onClick={() => {
              form.resetFields();
              props.onReset();
            }}>
              {t['button.reset']}
            </Button>
          </Space>
        </Row>
      </Row>
    </Form>
  );
};

export default () => {
  const t = useLocale(locale);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState<PaginationProps>({ ...defaultPaginationProps, pageSize: 12 });
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState<{
    id?: number,
    name?: string,
    code?: string,
    remark?: string,
    enabled?: string,
    activateState?: string,
    runningState?: string,
    structureIds?: number[] | null
  }>({});

  function fetchDevicePage(query) {
    const { current, pageSize } = pagination;
    setLoading(true);
    instance
      .post('/api/device/page', {
        pager: {
          pageNumber: current,
          pageSize: pageSize
        },
        query: query
      })
      .then((res) => {
        setData(res.data.data);
        setPagination({
          ...pagination,
          total: res.data.total
        });
      })
      .finally(() => {
        setTimeout(() => setLoading(false), 2000);
      });
  }

  function onSelectFactoryStructure(ids) {
    setQuery({
      ...query,
      structureIds: ids
    });
    setPagination({
      ...pagination,
      current: 1
    });
  }

  function onChangePagination(pageNumber: number, pageSize: number) {
    setPagination({
      ...pagination,
      current: pageNumber,
      pageSize: pageSize
    });
  }

  useEffect(() => {
    fetchDevicePage(query);
  }, [query, pagination.pageSize, pagination.current]);

  return (
    <Row gutter={24} style={{ minHeight: '80vh' }}>
      <Col span={4}>
        <FactoryStructurePanel onSelected={onSelectFactoryStructure} />
      </Col>
      <Col span={20}>
        <Row gutter={14} style={{ background: 'white', padding: '1rem' }}>
          <SearchForm onSubmit={it => setQuery({ ...it, structureIds: query.structureIds })}
                      onReset={() => setQuery({ structureIds: query.structureIds })} />
        </Row>
        <Row gutter={14} style={{ background: 'white', padding: '2rem 1rem', marginTop: '1rem' }}>
          <Col span={24}>
            {!!loading ? (
              <Skeleton animation />
            ) : (
              <Grid cols={4} colGap={12} rowGap={16}>
                {data.map((record) =>
                  <Grid.GridItem key={'device_card_grid_item_' + record.id}>
                    <NavLink
                      style={{ textDecoration: 'none' }}
                      key={'device_card_link_' + record.id}
                      to={'/monitor/device?id=' + record.id}>
                      <Card style={{ minWidth: '10rem', maxWidth: '20rem', minHeight: '5rem', background: '#eeeeee' }}
                            hoverable>
                        <Row gutter={24} align={'center'} justify={'space-between'}>
                          <Col span={6} style={{ height: '4rem', overflow: 'hidden' }}>
                            <img
                              height={'100%'}
                              style={{ objectFit: 'cover' }}
                              alt="dessert"
                              src="//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a20012a2d4d5b9db43dfc6a01fe508c0.png~tplv-uwbnlip3yd-webp.webp"
                            />
                          </Col>
                          <Col span={18} style={{}}>
                            <Row>
                              <Col span={24}>
                                <div> {record.name} </div>
                              </Col>
                              <Col span={24}>
                                <div> {record.code} </div>
                              </Col>
                              {
                                'ACTIVATED' === record.activateState.toString() &&
                                <Col span={24}>
                                  <div
                                    style={{ background: resolveDeviceRunningStateColor(record.runningState) }}></div>
                                  <div> {resolveDeviceRunningState(record.runningState)} </div>
                                </Col>
                              }
                              {
                                'ACTIVATED' !== record.activateState.toString() &&
                                <Col span={24}>
                                  {resolveDeviceActivateState(record.activateState)}
                                </Col>
                              }
                            </Row>
                          </Col>

                        </Row>
                      </Card>
                    </NavLink>
                  </Grid.GridItem>
                )}
              </Grid>
            )}
            <Row style={{ marginTop: '1rem' }}>
              <Col span={24}>
                <Row justify={'end'}>
                  <Pagination showTotal
                              pageSize={pagination.pageSize} total={pagination.total}
                              onChange={onChangePagination} />
                </Row>
              </Col>
            </Row>
          </Col>
        </Row>
      </Col>
    </Row>
  );
}
